package com.lancer.dynamic.thread.pool.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

public class SystemUtils {

    // 判断当前操作系统类型
    public static String getOsName() {
        return System.getProperty("os.name").toLowerCase();
    }

    public static boolean isLinux() {
        return getOsName().contains("linux");
    }

    public static boolean isWindows() {
        return getOsName().contains("windows");
    }

    // 获取物理核心数（自动适配）
    public static int getPhysicalCoreCount() {
        try {
            if (isLinux()) {
                return getPhysicalCoreCountLinux();
            } else if (isWindows()) {
                return getPhysicalCoreCountWindows();
            } else {
                // 可扩展 macOS 或其他系统
                return Runtime.getRuntime().availableProcessors(); // fallback
            }
        } catch (Exception e) {
            // 异常时返回逻辑核心数
            return Runtime.getRuntime().availableProcessors();
        }
    }

    // Linux 实现
    public static int getPhysicalCoreCountLinux() throws IOException {
        Process process = Runtime.getRuntime().exec("grep -A 2 'core id' /proc/cpuinfo | grep '^core id'");
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        Set<String> coreIds = new HashSet<>();
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.contains("core id")) {
                coreIds.add(line.split(":")[1].trim());
            }
        }
        return coreIds.size();
    }

    // Windows 实现
    public static int getPhysicalCoreCountWindows() throws IOException, InterruptedException {
        Process process = Runtime.getRuntime().exec("wmic cpu get NumberOfCores");
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            if (!line.trim().isEmpty() && Character.isDigit(line.charAt(0))) {
                return Integer.parseInt(line.trim());
            }
        }
        return Runtime.getRuntime().availableProcessors(); // fallback
    }
}
